#include <glib.h>
#include <pthread.h>

#define TEST_THREAD_POOL_FIN 9999

GThreadPool *g_pool = NULL;

gint _test_thread_int_cmp_func(gconstpointer a, gconstpointer b, gpointer user_data)
{
    return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
}

static void test_thread_pool_func(gpointer data, gpointer user_data)
{
    g_print("tid %ld: get data: %d \n", (glong)pthread_self(), GPOINTER_TO_INT(data));

    g_usleep(50*1000);

    if(TEST_THREAD_POOL_FIN == GPOINTER_TO_INT(data)) {
        g_print("theadpool free \n");
        g_thread_pool_free(g_pool, TRUE, TRUE);
    }
}

gpointer test_thread_func(gpointer data)
{
    GThreadPool *pool = (GThreadPool *)data;

    g_thread_pool_set_max_threads(pool, 0, NULL);

    g_thread_pool_push(pool, GINT_TO_POINTER(99), NULL);
    g_thread_pool_push(pool, GINT_TO_POINTER(120), NULL);
    g_thread_pool_push(pool, GINT_TO_POINTER(101), NULL);
    g_thread_pool_push(pool, GINT_TO_POINTER(106), NULL);
    g_thread_pool_push(pool, GINT_TO_POINTER(203), NULL);
    g_thread_pool_push(pool, GINT_TO_POINTER(104), NULL);

    g_thread_pool_set_sort_function(pool, _test_thread_int_cmp_func, NULL);
    g_thread_pool_set_max_threads(pool, 1, NULL);

    g_thread_pool_push(pool, GINT_TO_POINTER(TEST_THREAD_POOL_FIN), NULL);

    return NULL;
}

void test_thread_pool(void)
{
    guint num = 0;
    GError *error = NULL;
    gint max_threads = 4; //set initial max threads to 4

    GThread *thd = NULL;

    g_pool = g_thread_pool_new(test_thread_pool_func, NULL, max_threads, TRUE, &error);

    thd = g_thread_new("thd", test_thread_func, g_pool);
    g_usleep(500*1000);
    g_thread_join(thd);
}

gint main(gint argc, gchar **argv)
{
    test_thread_pool();
}